package com.example.pei.ithinklearnt.view.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.present.addDynamicPresent;
import com.example.pei.ithinklearnt.present.addDynamicPresentImp;
import com.example.pei.ithinklearnt.view.interfaces.addDynamicInterface;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;

public class AddDynamicActivity extends AppCompatActivity implements addDynamicInterface {

    private addDynamicPresent mAddDynamicPresent;

    private ArrayList<String> selectedPhotos = new ArrayList<>();

    private Button button_addDynamic;
    private Button button_back;
    private EditText editText_content;
    private TextView textView_num;  //文字数量限制，最大150字

    //TODO 如果全部都是换行符。也能发送，这是不对的

    private String objectId;

    private SweetAlertDialog sweetAlertDialog ;

    private GridView gv;
    private int columnWidth;
    private GridAdapter gridAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_dynamic_);
        mAddDynamicPresent=new addDynamicPresentImp(this);
        sweetAlertDialog=new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        findWidgets();

         gv = findViewById(R.id.gv);
        //得到GridView中每个ImageView宽高
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gv.setNumColumns(cols);
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int columnSpace = getResources().getDimensionPixelOffset(R.dimen.space_size);
        columnWidth = (screenWidth - columnSpace * (cols-1)) / cols;
        gridAdapter = new GridAdapter();
        gv.setAdapter(gridAdapter);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             //   Toast.makeText(AddDynamicActivity.this,selectedPhotos.get(position)+" ~",Toast.LENGTH_SHORT).show();
                if (gridAdapter.getItemViewType(position) == gridAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(gridAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(selectedPhotos)
                                    .start(AddDynamicActivity.this);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(AddDynamicActivity.this);
                        }

            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&(requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {
                selectedPhotos.addAll(photos);
                //刷新
                gridAdapter.notifyDataSetChanged();
                //设置按钮的样式
                if(photos.size()>0) {
                    button_addDynamic.setTextColor(Color.parseColor("#3a3a3a"));
                    button_addDynamic.setClickable(true);
                }else if(isAllSpace(editText_content.getText().toString())){
                    button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));
                    button_addDynamic.setClickable(false);
                }
            }

        }
    }
    @Override
    public Activity getActivity() {
        return AddDynamicActivity.this;
    }

    @Override
    public void setAddButtonStype(boolean enable) {
        if(!enable){
            button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));
            button_addDynamic.setClickable(false);
        }else
        {
            button_addDynamic.setTextColor(Color.parseColor("#3a3a3a"));
            button_addDynamic.setClickable(true);
        }
    }

    @Override
    public void setSweetAlertDialog(boolean enable) {
        if(enable){
            sweetAlertDialog.show();
        }else{
            sweetAlertDialog.dismiss();
        }
    }

    @Override
    public void setTextViewNum(String num) {
        textView_num.setText(num);
    }

    private void findWidgets(){
        //找到导航栏
        RelativeLayout title=findViewById(R.id.add_dynamic_include);
        button_addDynamic=title.findViewById(R.id.btn_add);
        button_addDynamic.setTextColor(Color.parseColor("#a2a2a2"));

        button_back=title.findViewById(R.id.button_backward);
        editText_content=findViewById(R.id.et_content);
        button_back.setText("取消");
        TextView textView=findViewById(R.id.text_title) ;
        textView.setText("发技能");
        button_addDynamic.setText("发送");
        textView_num=findViewById(R.id.tv_num);

        editText_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {

                mAddDynamicPresent.textChanged();

            }
        });

        button_addDynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAddDynamicPresent.sendDynamic();
            }
        });
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isAllSpace(getContent())&&selectedPhotos.size()==0){//如果都是空的，直接退出好了
                    finish();
                }else {
                    AlertDialog alert = new AlertDialog.Builder(AddDynamicActivity.this).create();
                    // alert.setIcon(R.drawable.stop);
                    // alert.setTitle("返回？");
                    alert.setMessage("取消将丢失已经编辑的内容");
                    //添加取消按钮
                    alert.setButton(DialogInterface.BUTTON_NEGATIVE, "继续编辑", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    //添加"确定"按钮
                    alert.setButton(DialogInterface.BUTTON_POSITIVE, "仍要返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    });
                    alert.show();
                }
            }
        });
        button_addDynamic.setClickable(false);


        sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        sweetAlertDialog.setTitleText("上传中,请稍后");
        sweetAlertDialog.setCancelable(false);
        sweetAlertDialog.dismiss();
    }

    @Override
    public void setAddButtonClickable(boolean enable) {
        button_addDynamic.setClickable(enable);
    }

    @Override
    public String getContent() {
        return editText_content.getText().toString();
    }

    @Override
    public ArrayList<String> getPhotoList() {
        return selectedPhotos;
    }

    private class GridAdapter extends BaseAdapter {
        public final static int TYPE_ADD = 1;
        public final static int TYPE_PHOTO = 2;
        public final static int MAX = 9;




        @Override
        public int getItemViewType(int position) {
            return (position == selectedPhotos.size() && position != MAX) ? TYPE_ADD : TYPE_PHOTO;
        }
        @Override
        public int getCount() {
            //return listUrls.size();
            int count = selectedPhotos.size() + 1;
            if (count > MAX) {
                count = MAX;
            }
            return count;
        }

        @Override
        public String getItem(int position) {
            return selectedPhotos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if(getItemViewType(position)==TYPE_PHOTO) {
                // if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
                imageView.setLayoutParams(params);
                //    } else {
                //        imageView = (ImageView) convertView.getTag();
                //    }
                final RequestOptions options = new RequestOptions();
                options.centerCrop()
                        .placeholder(R.drawable.banner_default)
                        .error(R.drawable.banner_error);
                Glide.with(AddDynamicActivity.this)
                        .load(new File(getItem(position)))
                        .apply(options)
                        .thumbnail(0.1f)
                        .into(imageView);


            }else {
                //   if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
                imageView.setLayoutParams(params);

                //    }else {
                //        imageView = (ImageView) convertView.getTag();
                //    }
                imageView.setBackgroundResource(R.drawable.addphoto);

            }
            return convertView;
        }
    }

}
